var MAX_SIZE = 100;
var MAX_HEIGHT = 46;
var selectedImageItem = null;
var imageItems;
var data = [];
var permission = true;
var myDoc, pubDoc;

var config = (function () {
    var defaults = {'public':'公共图片', 'private':'我的图片'};
    return {
        push : function (key, value) {
            defaults [key] = value;
        },
        contains : function (key) {
            return key in defaults;
        },
        getLabel : function (key) {
            return defaults [key];
        },
        remove : function (key) {
            if (key in defaults)
                delete  defaults [key];
        },
        retain : function () {
            var a = [];
            for (var i = 0; i < arguments.length; i ++) {
                var value = arguments [i];
                if (typeof value === 'string') a.push (value);
                else if (value instanceof Array) a = a.concat (value);
            }

            for (i = 0; i < a.length; i ++) {
                if (!(a[i] in defaults)) delete defaults [a [i]];
            }
        },
        clear : function () {
            defaults = {'public':'公共图片', 'private':'我的图片'};
        },
        acceptTypes : /\.(jpg|jpeg|png|gif|zip|rar)$/i
    };
})();

var openerWindow = window.dialogArguments || window.opener;

var CONTEXT_PATH = (function getContext() {
    var webroot = document.location.href;
    webroot = webroot.substring(webroot.indexOf('//') + 2, webroot.length);
    webroot = webroot.substring(webroot.indexOf('/') + 1, webroot.length);
    webroot = webroot.substring(0, webroot.indexOf('/'));
    return webroot == '' ? '' : '/' + webroot;
})();

// patch for cross domain
var domainName = Parameters.getParameter ('domain');
if (domainName) {
    document.domain = domainName;
}

function getServerSideConfig () {
    var loading = document.getElementById ('loading-panel');
    myDoc = document.getElementById ('my-images');
    pubDoc = document.getElementById ('public-images');

    dw.ajax ({
        url: CONTEXT_PATH + '/uploader/config',
        method: 'GET',
        success : function (response) {
            var ssc = eval ('(' + response.responseText + ')');
            if ('isPublicSupported' in ssc)
                config.isPublicSupported = ssc ['isPublicSupported'];
            if ('canCreateFolder' in ssc)
                config.canCreateFolder = ssc ['canCreateFolder'];
            if ('canRemoveItems' in ssc)
                config.canRemoveItems = ssc ['canRemoveItems'];
            if ('selectionMode' in ssc)
                config.selectionMode = ssc ['selectionMode'];
            if ('allowUploadTypes' in ssc)
                config.acceptTypes = eval ('(' + ssc ['allowUploadTypes'] + ')');

            if (config.isPublicSupported)
                pubDoc.style.display = 'block';

            changeFolder ('private');
        },
        always : function () {
            var loading = document.getElementById ('loading-panel');
            if (loading) loading.style.display = 'none';
        }
    });
}

function loadImages () {
    var container = document.getElementById ('browser');
    container.innerHTML = '';
    imageItems = [];
    for (var i = 0; i < data.length; i ++) {
        var dataItem = data [i];
        config.push (dataItem.src, dataItem.name);
        container.appendChild (createItem (dataItem));
    }
    var loading = document.getElementById ('loading-panel');
    if (loading) loading.style.display = 'none';
    permission = true;
}

function createItem (dataItem) {
    var a = document.createElement ('a');
    a.className = 'image-item';
    a.href = 'javascript:void(0)';
    a.onclick = onItemClicked;
//    container.appendChild (a);
    imageItems.push (a);

    var div = document.createElement ('div');
    div.className = 'image-holder';
    a.appendChild (div);

    var d = document.createElement ('div');
    div.appendChild (d);
    d.className = 'img_border';

    var img = document.createElement ('img');
    img.src = dataItem.type == 'folder' ? 'resource/images/folder.png' : dataItem.src;
    if (dataItem.width > MAX_SIZE || dataItem.height > MAX_SIZE) {
        var n = Math.max (dataItem.width, dataItem.height);
        var scale = MAX_SIZE / n;
        img.style.width = parseInt (dataItem.width * scale, 10) + 'px';
        img.style.height = parseInt (dataItem.height * scale, 10) + 'px';
    }
    d.appendChild (img);

    div = document.createElement ('div');
    div.className = 'txt';
    div.innerHTML = dataItem.name;
    a.appendChild (div);

    return a;
}

function changeFolder (folderName) {
    var a = folderName.split ('/');
    if (a [0] == 'private') {
        myDoc.className = 'nav-item-selected';
        pubDoc.className = 'nav-item'
    } else {
        myDoc.className = 'nav-item';
        pubDoc.className = 'nav-item-selected'
    }
    var folder = document.getElementById ('folderName');
    if (folder.value != folderName) {
        fetchData (folderName);
        folder.value = folderName;
    }

    var panel = document.getElementById ('location-bar');
//    while (panel.firstChild) panel.removeChild (panel.firstChild);
    panel.innerHTML = '';
    var ul = document.createElement ('ul');
    ul.className = 'location';
    panel.appendChild (ul);
    for (var i = 0; i < a.length; i ++) {
        var path = a[i];
        if (path == '') continue;

        if (i != 0) {
            var separator = document.createElement ('li');
            separator.className = 'separator';
            ul.appendChild (separator);
        }

        var label = (config.contains(path)) ? config.getLabel (path) : path;
        var li = document.createElement ('li');
        li.innerHTML = '<a href="javascript:changeFolder(\'' + buildPath(a, i) + '\')">' + label + '</a>';
        ul.appendChild (li);
    }

    function buildPath (a, i) {
        var s = '';
        for (var j = 0; j <= i; j ++) {
            if (s.length > 0) s += '/';
            s += a[j];
        }
        return s;
    }
}

function fetchData (folder) {
    folder = folder || document.getElementById ('folder-path').value;
    if (selectedImageItem) {
        selectedImageItem = null;
        showImageInfo (null);
    }
    var loading = document.getElementById ('loading-panel');
    var container = document.getElementById ('browser');
    if (!loading) {
        var p = getPosition (container);
        loading = document.createElement ('div');
        loading.id = 'loading-panel';
        loading.style.position = 'absolute';
        loading.style.width = container.clientWidth + 'px';
        loading.style.height = container.clientHeight + 'px';
        loading.style.lineHeight = container.clientHeight + 'px';
        loading.style.left = p.x + 'px';
        loading.style.top = p.y + 'px';
        loading.style.textAlign = 'center';
        loading.style.display = 'none';
        loading.innerHTML = "<img src='resource/images/loading.gif' /> 正在获取图片...";
        document.body.appendChild (loading);
    }
    container.innerHTML = '';
    loading.style.display = 'block';
    dw.ajax ({
        url: CONTEXT_PATH + '/uploader/image-list',
        method: 'GET',
        data : {a:'image-list', path: folder},
        success : function (response) {
            data = eval ('(' + response.responseText + ')');
            config.retain (folder.split ('/'));
            loadImages ();
        },
        always : function () {
            var loading = document.getElementById ('loading-panel');
            if (loading) loading.style.display = 'none';
        }
    });
}

/*
 function SearchEvent () {
 //IE
 if (window.navigator.userAgent.indexOf('MSIE') >= 0) return window.event;
 var func = SearchEvent.caller;
 while (func)
 {
 var arg0 = func.arguments[0];
 if (arg0 && arg0.constructor)
 if (arg0.constructor.toString ().indexOf ("Event") >= 0)
 return arg0;
 func = func.caller;
 }
 return null;
 }
 */

function findCurrentElement () {
    if (window.event.srcElement)
        return window.event.srcElement;

    if (arguments [0] && arguments [0].target)
        return arguments [0].target;

    return null;
    /*
     var e = window.event;
     alert (window.event);
     alert (e.srcElement);
     if (!e)
     e = arguments [0];
     if (!e)
     return null;

     return e.srcElement || e.target;
     */
}

function onItemClicked () {
//    var e = findCurrentElement ();
    var e;
    if (window.event && window.event.srcElement)
        e = window.event.srcElement;
    else if (arguments [0] && arguments [0].target)
        e = arguments [0].target;
    if (!e) return;

    var tagName = e.nodeName.toLowerCase();
    while (tagName != 'a') {
        e = e.parentNode;
        tagName = e ? e.nodeName.toLowerCase() : null;
    }
    if (!e) return;

    var index = findElement (e);
    if (index > -1) {
        var item = data [index];
        if (item.type == 'folder') {
            var folderName = document.getElementById ('folderName').value + '/' + item.src;
            changeFolder (folderName);
            return;
        }
    }

    if (selectedImageItem == e) {
        e.className = 'image-item';
        selectedImageItem = null;
    } else {
        if (selectedImageItem != null) {
            selectedImageItem.className = 'image-item';
        }
        e.className = 'image-item-selected';
        selectedImageItem = e;
    }

    showImageInfo (selectedImageItem);
}

function findElement (a) {
    if (!imageItems) return -1;
    for (var i = 0; i < imageItems.length; i ++) {
        if (a == imageItems [i]) return i;
    }
    return -1;
}

function showImageInfo (a) {
    var index = findElement (a);
    var holder = document.getElementById ('image-sample');
    var info = document.getElementById ('info');
    if (index == -1) {
        holder.innerHTML = '';
        info.innerHTML = '';
        return;
    }
    var item = data [index];
    var html = '<img src="' + item.src + '" style="border:1px solid #ccc;';
    var w = item.width, h = item.height;
    if (h > MAX_HEIGHT) {
        var scale = MAX_HEIGHT / h;
        html += 'width:' + parseInt (w * scale, 10) + 'px;height:' + parseInt (h * scale, 10) + 'px';
    }
    html += '"/>';
    holder.innerHTML = html;

    html = "<div class='file-name'>" + item.name + '</div>';
    html += "<div class='detail'>" + item.type + '图像 &nbsp; 尺寸: ' + item.width + ' x ' +
        item.height + ' &nbsp; 最后修改时间：' + item.lastModify + '</div>';
    info.innerHTML = html;
}

function showDialog (id) {
    if (!permission) return;
    showMask ();
    var root = document.getElementById ('root');
    var dialog = document.getElementById (id);
    dialog.style.display = 'block';
    dialog.style.zIndex = 101;

    var W = root.clientWidth, H = root.clientHeight;
    var w = dialog.offsetWidth, h = dialog.offsetHeight;
    var x = (W - w) / 2, y = (H - h) / 2;
    dialog.style.left = x + 'px';
    dialog.style.top = y + 'px';
}

function showUploadDialog () {
    showDialog ('upload-panel');
}

function closeUploadDialog () {
    closeDialog ('upload-panel');
}

function closeDialog (id) {
    hideMask ();
    var dialog = document.getElementById (id);
    dialog.style.display = 'none';
}

function createFolder () {
    var currentFolder = document.getElementById ('folderName').value;
    var path = document.getElementById ('txt-folder-name').value;

    if (path == '' || path.replace(/^\s+|\s+$/g, '').length == 0) {
        alert ('请输入要创建的目录名称');
        return;
    }

    if (/[\\\/\*\?\s]/ig.test (path)) {
        alert ('无效的目录名称');
        return;
    }

    var folderName = buildPathLabel (currentFolder + '/' + path);
    dw.ajax ({
        url: CONTEXT_PATH + '/uploader/create-folder',
        method : 'POST',
        data : {a:'create-folder', folderName:folderName},
        success : function (response) {
            var result = eval ('(' + response.responseText + ')');
            if (result.status == 'ok') {
                setTimeout (function () {
                    var dataItem = {name:path, type:'folder',src:result.src};
                    data.push (dataItem);
                    config.push (result.src, path);
                    var a = createItem (dataItem);
                    var div = document.getElementById ('browser');
                    div.insertBefore (a, div.firstChild);
                }, 0);
            } else {
                alert (result ['cause']);
            }
        },
        always : function () {
            closeDialog ('create-folder');
        }
    });
}

function showMask () {
    var mask = document.getElementById ('mask');
    if (!mask) {
        mask = document.createElement ('div');
        mask.id = 'mask';
        mask.className = 'mask';
        document.body.appendChild (mask);
        var root = document.getElementById ('root');
        mask.style.width = root.offsetWidth + 'px';
        mask.style.height = root.offsetHeight + 'px';
    }
    mask.style.visibility = 'visible';
}

function hideMask () {
    var mask = document.getElementById ('mask');
    if (mask)
        mask.style.visibility = 'hidden';
}

function uploadFile () {
//    var opener = (/MSIE/i).test (navigator.userAgent) ? window.dialogArguments : window.opener;
    var form = document.getElementById ('uploadForm');
    form.action = CONTEXT_PATH + '/uploader/uploader';
    var file = document.getElementById ('file');
    if (file.value == '') {
        alert ('请选择图片');
        return;
    }
    if (!config.acceptTypes.test (file.value)) {
        alert ('不支持的图片格式，请选择\r\nGIF, JPEG或PNG格式的图片');
        return;
    }

    var c = document.getElementById ('folderName');
    var backup = c.value;
    c.value = buildPathLabel (backup);

    form.submit ();
    closeUploadDialog ();
    c.value = backup;
}

function selectImage () {
    if (!selectedImageItem) {
        alert ('请选择图片');
        return;
    }

    var index = findElement (selectedImageItem);
    if (index < 0) {
        alert ('请选择图片');
        return;
    }
    var item = data [index];
    openerWindow._setImage (item.src, item.width, item.height, item.name);
    window.close ();
}

function getPosition (e) {
    var p = {x:0, y:0, toString: function (){return "[" + this.x + ", " + this.y + "]";}};
    if (e.offsetLeft) p.x += e.offsetLeft;
    if (e.offsetTop)  p.y += e.offsetTop;
    var parentElement = e.offsetParent;
    while (parentElement && parentElement != document.body)
    {
        if (parentElement.offsetLeft) p.x += parentElement.offsetLeft;
        if (parentElement.offsetTop)  p.y += parentElement.offsetTop;

        parentElement = parentElement.offsetParent;
    }
    return p;
}

function buildPathLabel (path) {
    if (!path || path.replace (/^\s+|\s+$/ig, '') == 0)
        return path;
    if (path.charAt(0) == '/')
        path = path.substring (1);

    var a = path.split ('/');
    var s = a [0];
    for (var i = 1; i < a.length; i ++) {
        var part = a [i];
        if (config.contains (part))
            part = config.getLabel (part);
        s += '/' + part;
    }

    return s;
}